$(document).ready(function() {
    var location = $("#location");
    var login = $("#login");
    var fName = $("#first-name");
    var lName = $("#last-name");
    var country = $("#country");
    var city = $("#city");
    var street = $("#street");
    var home = $("#home");
    var appartment = $("#appartment");
    var email = $("#email");
    var password = $("#password");
    var confPassword = $("#confpassword");
    var latitude = $("#latitude");
    var longitude = $("#longitude");

    var loginTip = $("#loginTip");
    var fNameTip = $("#first-nameTip");
    var lNameTip = $("#last-nameTip");
    var countryTip = $("#countryTip");
    var cityTip = $("#cityTip");
    var streetTip = $("#streetTip");
    var homeTip = $("#homeTip");
    var appartmentTip = $("#appartmentTip");
    var emailTip = $("#emailTip");
    var passwordTip = $("#passwordTip");
    var confPasswordTip = $("#confpasswordTip");

    var loginPattern = "^[a-zA-Z]\\w{2,}$";
    var namePattern = "^[a-zA-Z][a-zA-Z ,.'-]*$";
    var addressPattern = "^[a-zA-Z ,.'-]+$";
    var homePattern = "^[a-zA-Z0-9,./'-]+$";
    var emailPattern = "(([A-Za-z])|(\\d)|([-_.]))+@([A-Za-z])+[.]([A-Za-z]){2,4}";
    var passwordPattern = "\\w{6,14}$";

    var res;
    //TODO selecting place
    function isEmptyFields() {
        var flag = true;
        flag = ($("#country").val() === "");
        flag = flag || ($("#city").val() === "");
        flag = flag || ($("#street").val() === "");
        flag = flag || ($("#home").val() === "");
        return flag;
    }


    function updateLocation() {
        location.show();
        getLocation();
        if (isEmptyFields()) {
            location.hide();
        }
    }

    login.keyup(function() {
        checkValidate(login, loginTip, loginPattern);
    });
    fName.keyup(function() {
        checkValidate(fName, fNameTip, namePattern);
    });
    lName.keyup(function() {
        checkValidate(lName, lNameTip, namePattern);
    });
    city.keyup(function() {
        checkValidate(city, cityTip, addressPattern);
        updateLocation();
    });
    country.keyup(function() {
        checkValidate(country, countryTip, addressPattern);
        updateLocation();
    });
    street.keyup(function() {
        checkValidate(street, streetTip, addressPattern);
        updateLocation();
    });
    home.keyup(function() {
        checkValidate(home, homeTip, homePattern);
        updateLocation();
    });
    appartment.keyup(function() {
        checkValidate(appartment, appartmentTip, homePattern);
        if (appartment.val() == "") {
            appartment.css("border-color", "#79c30c");
            appartmentTip.html("");
        }
    });
    email.keyup(function() {
        checkValidate(email, emailTip, emailPattern);
    });
    password.keyup(function() {
        checkValidate(password, passwordTip, passwordPattern);
    });
    confPassword.keyup(function() {
        checkValidateConfPassword(confPassword, password, confPasswordTip, passwordPattern);
    });

    $("#location").click(function() {
        var i = $("#location :radio:checked").attr("id");
        for (var k = 0; k < res[i].address_components.length; k++) {
            if (res[i].address_components[k].types[0] == "country")
                country.val(toTranslit(res[i].address_components[k].long_name));
            if (res[i].address_components[k].types[0] == "locality")
                city.val(toTranslit(res[i].address_components[k].long_name));
            if (res[i].address_components[k].types[0] == "route") 
                street.val(toTranslit(res[i].address_components[k].long_name));
            if (res[i].address_components[k].types[0] == "street_number")
                home.val(toTranslit(res[i].address_components[k].long_name));
        }
        
        setMarkerPosition(res, i);
    });

    function callback(param) {
        res = param;
        showAddresses();
    }

    function showAddresses() {
        if (res.length === 0) {
            location.hide();
        }
        var str = '<div class="block-header-item"><h3>Choose your location: <span class="text-red">*</span></h3></div>';
        for (var i = 0; i < res.length; i++) {
            str += '<div class="box" style="padding: 10px;"><input type="radio" name="location" id="';
            str += i + '" ';
            str += '>' + res[i].formatted_address;
            str += '</div>';
        }
        setMarkerPosition(res, 0);
        $('#location').html(str);
        var radio = $("#location div #0");
        $(radio).attr("checked", "checked");
    }

    function getLocation() {
        var address = $("#country").val() +
                ", " +
                $("#city").val() +
                ", " +
                $("#street").val() +
                ", " +
                $("#home").val();
        codeAddress(address, callback);
    }

    $("#reg-btn").unbind('click').click(function(event) {

        $(".table-view .error").each(function() {
            $(this).html("");
        });
        $(":input").each(function() {
            $(this).css("border-color", "#CCC");
        });

        checkValidate(login, loginTip, loginPattern);
        checkValidate(fName, fNameTip, namePattern);
        checkValidate(lName, lNameTip, namePattern);
        checkValidate(city, cityTip, addressPattern);
        checkValidate(country, countryTip, addressPattern);
        checkValidate(street, streetTip, addressPattern);
        checkValidate(home, homeTip, homePattern);
        checkValidate(email, emailTip, emailPattern);
        checkValidate(password, passwordTip, passwordPattern);
        checkValidateConfPassword(confPassword, password, confPasswordTip, passwordPattern);

        if (appartment.val() != "") {
            checkValidate(appartment, appartmentTip, homePattern);
        }

        if (checkValidate(login, loginTip, loginPattern)
                & checkValidate(fName, fNameTip, namePattern)
                & checkValidate(lName, lNameTip, namePattern)
                & checkValidate(city, cityTip, addressPattern)
                & checkValidate(country, countryTip, addressPattern)
                & checkValidate(street, streetTip, addressPattern)
                & checkValidate(home, homeTip, homePattern)
                & checkValidate(email, emailTip, emailPattern)
                & checkValidate(password, passwordTip, passwordPattern)
                & checkValidateConfPassword(confPassword, password, confPasswordTip, passwordPattern)) {
            sendData();
        }
    });

    function sendData() {
        var dataString = 'login=' + login.val() +
                '&fName=' + fName.val() +
                '&lName=' + lName.val() +
                '&password=' + password.val() +
                '&email=' + email.val() +
                '&country=' + country.val() +
                '&city=' + city.val() +
                '&street=' + street.val() +
                '&home=' + home.val() +
                '&appartment=' + appartment.val() +
                '&latitude=' + latitude.val() +
                '&longitude=' + longitude.val();
        $.ajax({
            type: "POST",
            url: "Registration",
            data: dataString,
            success: function(data) {
                loginTip.html(data.login);
                countryTip.html(data.country);
                cityTip.html(data.city);
                emailTip.html(data.email);
                fNameTip.html(data.fName);
                homeTip.html(data.home);
                lNameTip.html(data.lName);
                passwordTip.html(data.password);
                streetTip.html(data.street);
                if (typeof data.success !== "undefined")
                    showDialog();
            }
        });
    }

    function showDialog() {
        var dialog = '<div id="dark-font"></div>'
                + '<div id="dialog-outer">'
                + '<div id="dialog">'
                + '<h1>Congratulations!</h1>'
                + 'You are registered on our web-site. Detailed information sent to your email.'
                + '<div style="text-align: center; margin-top: 30px;">'
                + '<input type="button" value="Main page" id="main-page"/>'
                + '<input type="button" value="Sign in" id="sign-in"/>'
                + '</div></div></div>';
        $("#content").after(dialog);
        $("#main-page").click(function() {
            document.location.href = "index.jsp";
        });
        $("#sign-in").click(function() {
            document.location.href = "index.jsp?content=signin";
        });
    }
});